#!/usr/bin/python2.7
"Decodes TrickBot core modules from the dumped loaders' resources"
__AUTHOR__ = 'hasherezade'

import argparse

def decode(data):
    decoded = bytearray()
    key = 0x3039
    i = 0
    for i in range(0, len(data)):
        dec_val = data[i] ^ (key & 0xFF)
        key *= 0x0AE529
        key += 0x24D69
        decoded.append(dec_val)
    return decoded

def find_pe(data):
    while len(data):
        mz_start = data.find('MZ')
        if mz_start == -1:
            return None
        pe_start = data[mz_start:]
        data = data[mz_start + len('MZ'):]
        pe = data.find('PE')
        if pe != -1:
            return pe_start
    return None

def dump_to_file(filename, data):
    with open(filename, 'wb') as f:
        f.write(data)

def main():
    parser = argparse.ArgumentParser(description="TrickBot payload decoder")
    parser.add_argument('--datafile',dest="datafile",default=None,help="File with data", required=True)
    parser.add_argument('--pe_name',dest="pe_name",default="trick_payload.exe", help="Where to dump the PE", required=False)
    parser.add_argument('--outfile',dest="outfile",default="out.bin", help="Where to dump the output")
    args = parser.parse_args()

    data = bytearray(open(args.datafile, 'rb').read())
       
    decoded = decode(data)
    dump_to_file(args.outfile, decoded)
    print "Dumped decoded to: %s" % (args.outfile)

    pe_data = find_pe(decoded)
    if pe_data is None:
        print "No PE file found!"
        return

    dump_to_file(args.pe_name, pe_data)
    print "Extracted PE to: %s" % (args.pe_name)

if __name__ == '__main__':
    main()
